import 'dart:async';

import 'package:fig/events/spider_event.dart';
import 'package:fig/models/media_category.dart';
import 'package:fig/sqlite/table_media_category.dart';
import 'package:fig/utils/config.dart';
import 'package:fig/views/home/category_detail_widget.dart';
import 'package:fig/views/home/setting.dart';
import 'package:flutter/material.dart';

import 'no_data_widget.dart';

class HomeScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => HomeScreenState();
}

class HomeScreenState extends State<HomeScreen> {
  var categoryInit = false;
  final categoryTabs = [MediaCategory(id: 0, title: 'OOPS', originId: 0)];

  StreamSubscription<SpiderChangedEvent> _spiderChangedSub;

  void loadData() async {
    TableMediaCategory().getCategories().then((categories) {
      print('loadData getCategories ${categories.length}');
      if (categories.length > 0) {
        setState(() {
          categoryInit = true;
          categoryTabs.clear();
          categoryTabs.addAll(categories);
        });
      }
    });
  }

  @override
  void initState() {
    print('HomeScreenState initState');
    super.initState();

    // 注册事件监听
    _spiderChangedSub = Config.eventBus.on<SpiderChangedEvent>().listen((event) => loadData());

    loadData();

  }

  @override
  void dispose() {
    super.dispose();
    _spiderChangedSub.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: categoryTabs.length,
      child: Scaffold(
        appBar: AppBar(
          actions: [
            IconButton(
              icon: const Icon(Icons.settings),
              onPressed: () {
                Navigator.push(context, new MaterialPageRoute(builder: (context) => HomeSettingPageWidget()));
              },
            ),
          ],
          automaticallyImplyLeading: false, // 设置没有返回按钮
          title: Text('无花果电影'),
          bottom: TabBar(
            // indicatorPadding: EdgeInsets.fromLTRB(1000, 0, 10, 0), // 好像没什么效果
            isScrollable: true, // 是否可滚动
            indicatorWeight: 2.0, // 指示器的高度
            labelStyle: TextStyle(fontSize: 16.0), // 标签栏文字大小
            tabs: [
              for (final categoryTab in categoryTabs) Tab(text: categoryTab.title),
            ],
          ),
        ),
        body: TabBarView(
          children: categoryInit
              ? [
                  for (final category in categoryTabs)
                    Center(
                      key: UniqueKey(),
                      child: CategoryDetailWidget(category.originId),
                    ),
                ]
              : [
                  Center(
                    key: UniqueKey(),
                    child: HomeNoDataWidget(),
                  )
                ],
        ),
      ),
    );
  }
}
